package com.yeb.server.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 登录授权过滤器
 * OncePerRequestFilter:它能够确保在一次请求中只通过一次 filter，而不需要重复的执行
 */
public class  JwtAuthenticationFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException { // 前置拦截器
        // 根据请求头名称: Authorization 获取请求头信息，这里是获取 token
        // Authorization: <type> <credentials> : <Bearer> <token>
        String authHeader = request.getHeader(tokenHeader);
        // 存在 token
        if(null!=authHeader && authHeader.startsWith(tokenHead)){
            // 截取字符串 
            String authToken = authHeader.substring(tokenHead.length());// 这里是开始的位置 beginIndex，从0开始
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            // token 存在用户名但未登录,也就是说其之前登陆过，现在退出登入了
            if(null!=username && SecurityContextHolder.getContext().getAuthentication()==null){
                //登录
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                //验证 token 是否有效，重新设置用户对象
                if(jwtTokenUtil.validateToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                            userDetails,null,userDetails.getAuthorities()
                    );
                    //从 request 中构建详细的用户认证信息，比如验证码，用户类型等
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    //将认证信息加入到 security 全局上下文中
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        // 放行
        filterChain.doFilter(request,response);
    }
}
